package top.tupobi.zing.custom_view;

import android.Manifest;
import android.animation.AnimatorSet;
import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.zyyoona7.popup.EasyPopup;
import com.zyyoona7.popup.XGravity;
import com.zyyoona7.popup.YGravity;

import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import top.tupobi.zing.InfoRecord;
import top.tupobi.zing.R;
import top.tupobi.zing.adapter.AdapterRvFriendList;
import top.tupobi.zing.adapter.OnItemTouchCallback;
import top.tupobi.zing.listener.OnFriendChooseChangeListener;
import top.tupobi.zing.mvp.model.FriendModel;
import top.tupobi.zing.network.HttpConfig;
import top.tupobi.zing.utils.PermissionRequestCallback;
import top.tupobi.zing.utils.PermissionUtils;

public class LeftMenu extends LinearLayout {

    private LeftMenu(Context context) {
        super(context);
    }

    public static class Builder {
        public static final int PICK_PHOTO = 102;

        private static final int sMenuStateOpened = 777;
        private static final int sMenuStateOpening = 778;
        private static final int sMenuStateClosed = 779;
        private static final int sMenuStateClosing = 780;

        private int mMenuCurrentState = sMenuStateClosed;

        private LeftMenu mLeftMenu;
        private View mMaskView;
        private RelativeLayout rl_root_view;
        private int width, height;
        private View mView;
        private boolean mIsEnableTouchOutsideClose = true;
        private CircleImageView iv_avatar;
        private TextView tv_nickname;
        private View view_dot;
        private FragmentActivity mActivity;
        private RecyclerView rv_friend_list;
        private LinearLayout ll_friend;
        private EasyPopup mFriendPop;
        private OnLeftMenuListener mOnLeftMenuListener;
        private AdapterRvFriendList mAdapterRvFriendList;
        private OnFriendChooseChangeListener mOnFriendChooseChangeListener;
        private View rv_chat;

        public void setOnFriendChooseChangeListener(OnFriendChooseChangeListener onFriendChooseChangeListener) {
            mOnFriendChooseChangeListener = onFriendChooseChangeListener;
        }

        public void setOnLeftMenuListener(OnLeftMenuListener onLeftMenuListener) {
            mOnLeftMenuListener = onLeftMenuListener;
        }

        public Builder(FragmentActivity activity, View rv_chat) {
            mActivity = activity;
            RelativeLayout rootView2Attach = (RelativeLayout) ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0);
            mLeftMenu = new LeftMenu(activity);
            mMaskView = new View(activity);
            rl_root_view = rootView2Attach;
            this.rv_chat = rv_chat;
            mView = LayoutInflater.from(activity).inflate(R.layout.left_menu, mLeftMenu, true);
            initView();
        }

        private void initView() {
            view_dot = mView.findViewById(R.id.view_dot);
            iv_avatar = mView.findViewById(R.id.iv_avatar);
            ll_friend = mView.findViewById(R.id.ll_friend);
            tv_nickname = mView.findViewById(R.id.tv_nickname);
            rv_friend_list = mView.findViewById(R.id.rv_friend_list);

            initFriendPop();

            String nickname = InfoRecord.getNickname();
            String avatarUrlPath = InfoRecord.getAvatarUrl();
            if (!StringUtils.isEmpty(nickname)) {
                tv_nickname.setText(nickname);
            }
            if (!StringUtils.isEmpty(avatarUrlPath)) {
                Glide.with(mView).load(HttpConfig.PIC_ROOT + avatarUrlPath).into(iv_avatar);
            }

            rv_friend_list.setLayoutManager(new LinearLayoutManager(mActivity));
            mAdapterRvFriendList = new AdapterRvFriendList();
            mAdapterRvFriendList.setOnItemTouchCallback(new OnItemTouchCallback() {

                @Override
                public void onClick(View v, FriendModel friendModel) {
                    if (mOnFriendChooseChangeListener != null) {
                        closeMenu();
                        mOnFriendChooseChangeListener.onFriendChooseChangeListener(friendModel);
                    }
                }

                @Override
                public void onCloseMenu() {
                    closeMenu();
                }
            });
            rv_friend_list.setAdapter(mAdapterRvFriendList);
            setListener();
        }

        private void initFriendPop() {
            mFriendPop = EasyPopup.create()
                    .setContentView(mLeftMenu.getContext(), R.layout.pop_friend)
                    .setAnimationStyle(R.style.TopPopAnim)
                    .setFocusAndOutsideEnable(true)
                    .setFocusAndOutsideEnable(true)
                    .setBackgroundDimEnable(true)
                    .setDimValue(0.4f)
                    .setDimView(mLeftMenu)
                    .setOnViewListener((view, popup) -> {
                        view.findViewById(R.id.tv_add_friend).setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mOnLeftMenuListener.onAddFriend();
                                popup.dismiss();
                            }
                        });
                        view.findViewById(R.id.tv_apply_list).setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mOnLeftMenuListener.onShowFriendApplyList();
                                popup.dismiss();
                            }
                        });
                        if (InfoRecord.getHasNewFriend()) {
                            view.findViewById(R.id.view_dot).setVisibility(VISIBLE);
                        } else {
                            view.findViewById(R.id.view_dot).setVisibility(GONE);
                        }
                    }).apply();
        }

        private void setListener() {
            ll_friend.setOnClickListener(v -> mFriendPop.showAtAnchorView(v, YGravity.BELOW, XGravity.CENTER, 0, 0));
            mView.setOnClickListener(v -> {
            });
            iv_avatar.setOnClickListener(v -> openGallery());
            tv_nickname.setOnClickListener(v -> showInputDialog());

            final float[] outMenuFromX = new float[1];
            final boolean[] shouldSlideMenu = {false};
            rv_chat.setOnTouchListener((v, event) -> {
                if (mMenuCurrentState == sMenuStateOpened) {
                    if (mIsEnableTouchOutsideClose) {
                        closeMenu();
                    } else {
                        // do nothing
                    }
                    return true;
                }
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_POINTER_DOWN:
                        //除了第一个手指以外的手指按下
                        break;
                    case MotionEvent.ACTION_DOWN:

                        if (KeyboardUtils.isSoftInputVisible(mActivity)) {
                            KeyboardUtils.hideSoftInput(mActivity);
                        }

                        if (mMenuCurrentState == sMenuStateClosed) {
                            if (event.getX() <= rl_root_view.getWidth() / 3) {
                                outMenuFromX[0] = event.getX();
                                shouldSlideMenu[0] = true;
                                return true;
                            } else {
                                shouldSlideMenu[0] = false;
                                return false;
                            }
                        }
                        break;
                    case MotionEvent.ACTION_MOVE:
                        break;
                    case MotionEvent.ACTION_UP:
                        if (shouldSlideMenu[0]) {
                            float outMenuEndX = event.getX();
                            float distance = outMenuEndX - outMenuFromX[0];
                            if (distance > 150) {
                                openMenu();
                                shouldSlideMenu[0] = false;
                                return true;
                            }
                        }
                        break;
                }
                return false;
            });

            final float[] insideMenuFromX = {0};
            final float[] insideMenuFirstMoveX = {0};
            final boolean[] insideMenuIsFirstMove = {true};
            rv_friend_list.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    int action = event.getAction();
                    switch (action) {
                        case MotionEvent.ACTION_POINTER_DOWN:
                            //除了第一个手指以外的手指按下
                            break;
                        case MotionEvent.ACTION_DOWN:
                            insideMenuFromX[0] = event.getX();
                            LogUtils.e("insideMenuFromX == " + insideMenuFromX[0]);
                            break;
                        case MotionEvent.ACTION_MOVE:
                            if (insideMenuIsFirstMove[0]) {
                                insideMenuFirstMoveX[0] = event.getX();
                                insideMenuIsFirstMove[0] = false;
                            }
                            break;
                        case MotionEvent.ACTION_UP:
                            float endX = event.getX();
                            LogUtils.e("endX == " + endX);
                            if (insideMenuFromX[0] == 0) {
                                insideMenuFromX[0] = insideMenuFirstMoveX[0];
                            }
                            float distance = insideMenuFromX[0] - endX;
                            LogUtils.e("distance == " + distance);
                            insideMenuFromX[0] = 0;
                            insideMenuFirstMoveX[0] = 0;
                            if (distance > 40) {
                                closeMenu();
                                return true;
                            }
                            break;
                    }
                    return false;
                }
            });

            mLeftMenu.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    int action = event.getAction();
                    switch (action) {
                        case MotionEvent.ACTION_POINTER_DOWN:
                            //除了第一个手指以外的手指按下
                            break;
                        case MotionEvent.ACTION_DOWN:
                            insideMenuFromX[0] = event.getX();
                            LogUtils.e("insideMenuFromX == " + insideMenuFromX[0]);
                            break;
                        case MotionEvent.ACTION_MOVE:
                            LogUtils.e("insideMenu move");
                            break;
                        case MotionEvent.ACTION_UP:
                            LogUtils.e("insideMenu up");
                            float endX = event.getX();
                            LogUtils.e("endX == " + endX);
                            float distance = insideMenuFromX[0] - endX;
                            LogUtils.e("distance == " + distance);
                            if (distance > 40) {
                                closeMenu();
                                return true;
                            }
                            break;
                    }
                    return false;
                }
            });
        }

        private void openGallery() {
            //动态申请获取访问 读写磁盘的权限
            if (PermissionUtils.hasThePermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, mActivity)) {
                //打开相册
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                //Intent.ACTION_GET_CONTENT = "android.intent.action.GET_CONTENT"
                intent.setType("image/*");
                mActivity.startActivityForResult(intent, PICK_PHOTO); // 打开相册
            } else {
                PermissionUtils.requestAPermissionWithRx(mActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE, new PermissionRequestCallback() {
                    @Override
                    public void onPermissionGranted(List<String> data) {

                    }

                    @Override
                    public void onPermissionRejected(List<String> data) {

                    }

                    @Override
                    public void onPermissionRationale() {

                    }
                });
            }
        }

        private void showInputDialog() {
            if (mOnLeftMenuListener != null) {
                mOnLeftMenuListener.onUploadNickname();
            }
        }

        private void initMenu() {
            width = rl_root_view.getWidth() * 3 / 4;
            height = rl_root_view.getHeight();
            mLeftMenu.setVisibility(GONE);

            mLeftMenu.post(() -> {
                ViewGroup.LayoutParams layoutParams = mView.getLayoutParams();
                layoutParams.width = width;
                layoutParams.height = height;
                mView.setLayoutParams(layoutParams);
                mLeftMenu.setVisibility(VISIBLE);
            });

            mMaskView.post(() -> {
                ViewGroup.LayoutParams maskViewLayoutParams = mMaskView.getLayoutParams();
                maskViewLayoutParams.width = rl_root_view.getWidth();
                maskViewLayoutParams.height = rl_root_view.getHeight();
                mMaskView.setBackgroundColor(0x00ffffff);
                mMaskView.setLayoutParams(maskViewLayoutParams);
            });
        }

        public Builder setFriendList() {
            return this;
        }

        public void openMenu() {
            if (mMenuCurrentState != sMenuStateClosed) {
                return;
            }
            initMenu();
            // 为父布局添加蒙层
            rl_root_view.addView(mMaskView);
            // 左边添加该菜单
            rl_root_view.addView(mLeftMenu);
            final MarginLayoutParams marginLayoutParams = (MarginLayoutParams) mView.getLayoutParams();

            AnimatorSet animatorSet = new AnimatorSet();
            ValueAnimator slideAnimator = ValueAnimator.ofInt(-width, 0);

            slideAnimator.addUpdateListener(animation -> {
                int currentMarginLeft = (int) animation.getAnimatedValue();
                marginLayoutParams.setMargins(currentMarginLeft, marginLayoutParams.topMargin, marginLayoutParams.rightMargin, marginLayoutParams.bottomMargin);
                mView.setLayoutParams(marginLayoutParams);
                if (currentMarginLeft == 0) {
                    mMenuCurrentState = sMenuStateOpened;
                }
            });
            animatorSet.playTogether(
                    slideAnimator,
                    ObjectAnimator.ofObject(rl_root_view.getChildAt(rl_root_view.getChildCount() - 2), "backgroundColor", new ArgbEvaluator(),
                            0x00000000, 0x4D000000)
            );
            animatorSet.setInterpolator(new DecelerateInterpolator());
            animatorSet.setDuration(300).start();
            mMenuCurrentState = sMenuStateOpening;
        }

        private void closeMenu() {
            if (mMenuCurrentState != sMenuStateOpened) {
                return;
            }
            AnimatorSet animatorSet = new AnimatorSet();

            final MarginLayoutParams marginLayoutParams = (MarginLayoutParams) mView.getLayoutParams();
            ValueAnimator slideAnimator = ValueAnimator.ofInt(0, -width);

            slideAnimator.addUpdateListener(animation -> {
                int currentMarginLeft = (int) animation.getAnimatedValue();
                marginLayoutParams.setMargins(currentMarginLeft, marginLayoutParams.topMargin, marginLayoutParams.rightMargin, marginLayoutParams.bottomMargin);
                mView.setLayoutParams(marginLayoutParams);
                if (currentMarginLeft == -width) {
                    mView.setVisibility(GONE);
                    rl_root_view.removeView(mLeftMenu);
                    rl_root_view.removeView(mMaskView);
                    mMenuCurrentState = sMenuStateClosed;
                }
            });
            animatorSet.playTogether(
                    slideAnimator,
                    ObjectAnimator.ofObject(rl_root_view.getChildAt(rl_root_view.getChildCount() - 2), "backgroundColor", new ArgbEvaluator(),
                            0x4D000000, 0x00000000)
            );
            animatorSet.setInterpolator(new DecelerateInterpolator());
            animatorSet.setDuration(300).start();
            mMenuCurrentState = sMenuStateClosing;
        }

        public boolean isMenuOpened() {
            return mMenuCurrentState == sMenuStateOpened;
        }

        public Builder setmIsEnableTouchOutsideClose(boolean mIsEnableTouchOutsideClose) {
            this.mIsEnableTouchOutsideClose = mIsEnableTouchOutsideClose;
            return this;
        }

        public void setAvatar(String avatarUrl) {
            Glide.with(mView).load(avatarUrl).into(iv_avatar);
        }

        public void setNickname(String nickname) {
            tv_nickname.setText(nickname);
        }

        public void setHasNewFriendDot() {
            view_dot.setVisibility(VISIBLE);
            initFriendPop();
        }

        public void refreshFriendList(List<FriendModel> friendList) {
            if (friendList != null && friendList.size() > 0) {
                String currentChatFriendJson = InfoRecord.getCurrentChatFriendJson();
                if (StringUtils.isEmpty(currentChatFriendJson)) {
                    mOnFriendChooseChangeListener.onFriendChooseChangeListener(friendList.get(0));
                } else {
                    mOnFriendChooseChangeListener.onFriendChooseChangeListener(new Gson().fromJson(currentChatFriendJson, FriendModel.class));
                }
                mAdapterRvFriendList.notifyFriendListChanged(friendList);
            }
        }
    }
}
